package net.zjitc.dao.impl;

import net.zjitc.dao.UserDao;
import net.zjitc.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by lkj10 on 2017/2/28.
 */
@Repository
public class UserDaoImpl implements UserDao {
   /* private User[] users=new User[3];
    public void init(){
        users[0]=new User(1, "lkj","123");
        users[1]=new User(2,"lh","123");
        users[2]=new User(3,"qqq","123");
    }*/
   protected Session getSession(){
       Session session=sessionFactory.getCurrentSession();
       return session;
   }
   @Resource
   private SessionFactory sessionFactory;
    @Override

    public boolean fingByUser(String username) {
        /*this.init();
//       遍历
        for (User u:users){
            if (u.getUsername().equals(username)){
                return u;
            }
        }*/

        /*Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();*/
        User user = (User)getSession().createQuery("from User u where u.username=?")
                .setParameter(0,username)
                .uniqueResult();
        if(user!=null){
           /* transaction.commit();
            session.close();*/
            return true;
        }

        return false;
    }
    @Override
    public void register(String username, String password) {
        Session session=sessionFactory.getCurrentSession();
       /* Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();*/
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        session.save(user);
        /*transaction.commit();
        session.close();*/
    }

    @Override
    public List<User> findAll() {
        return getSession().createQuery("from User").list();
    }
}
